from flask import g
from flask_restful import Resource
from flask_restful.reqparse import RequestParser
from comment.modules.bank_card import BankCard
from comment.modules.user import User
from comment.utils.decorators import login_required
from comment.modules import db


class Card_Resource(Resource):
    """
    银行卡管理的资源类
    """
    # 使用了登录拦截的装饰器
    method_decorators = [login_required]

    def post(self):
        uid = g.user_id
        login_user = User.query.filter(User.id == uid).first()

        rp = RequestParser()
        rp.add_argument('holder', required=True) # 持卡人（账户名字）
        rp.add_argument('openingBank', required=True)  # 开户银行
        rp.add_argument('bankBranch', required=True)  # 支行
        rp.add_argument('cityId', required=True)  # 城市id
        rp.add_argument('cardNum', required=True)  # 卡片号码

        args = rp.parse_args()

        holder = args.holder
        opening_bank = args.openingBank
        bank_branch = args.bankBranch
        city_id = args.cityId
        bank_card_num = args.cardNum

        # 验证银行卡是否唯一
        card_info = BankCard.query.filter(BankCard.bankCardNum == bank_card_num).first()
        if card_info:
            return {'message': '银行卡已经存在，请勿重复添加', 'code': 20001}

        # 把银行卡数据保持到数据库
        card = BankCard(bankCardNum=bank_card_num, openingBank=opening_bank, holder=holder,
                        bankBranch=bank_branch, cityId=city_id, userId=uid, reservePhone=login_user.phone)

        db.session.add(card)
        db.session.commit()
        return {'msg': 'success'}

    def get(self):
        """
        查询当前登录用户所拥有的银行卡列表
        :return:
        """
        uid = g.user_id

        # 查询数据库中，当前用户下所有的银行卡
        card_list = BankCard.query.filter(BankCard.userId == uid).all()

        from financial.resources.card.serializer import BankCardListSerializer
        if card_list:  # 把对象转换成字典数据
            return BankCardListSerializer(card_list).to_dict()
        else:
            return {}

    def delete(self):
        rp = RequestParser()
        rp.add_argument('cardNum', required=True)

        args = rp.parse_args()
        bankCardNum = args.cardNum

        cardInfo = BankCard.query.filter(BankCard.bankCardNum == bankCardNum)
        if cardInfo:
            cardInfo.delete()
            db.session.commit()
            return {'msg': 'success'}
        else:
            return {"code": 20008, 'message': 'no this card'}